﻿#include "dbstruct.h"

CSqlDllOper::CSqlDllOper(QString sTableName, QString sConfigPath, QString sDllPath)
{
	m_pSqlOper = nullptr;
	m_bStart = false;
	m_sTableName = sTableName;
	m_sConfigPath = sConfigPath;
	m_sDllPath = sDllPath;
}
CSqlDllOper::~CSqlDllOper()
{
	unLoadLibrary();
}
bool CSqlDllOper::initSql()
{
	if (m_pSqlOper == nullptr)
	{
		if (!loadLibrary())
		{
			return false;
		}
	}
	QFile file(m_sConfigPath);
	if (!file.open(QIODevice::ReadOnly))
	{
		return false;
	}

	QDomDocument doc;
	if (!doc.setContent(&file))
	{
		file.close();
		return false;
	}
	file.close();

	QDomElement root = doc.documentElement();
	if (root.tagName() != "HKAI")
	{
		return false;
	}
	CDataBaseConfig cCfg;
	QDomElement mysqlElem = root.firstChildElement("MYSQL").firstChildElement("ConnectInfo");
	if (mysqlElem.isNull())
	{
		return false;
	}
	QStringList parts = mysqlElem.attribute("ConnectInfo").split(";");
	if (parts.size() < 5)
	{
		return false;
	}
	cCfg.sName = parts[0];
	cCfg.nPort = parts[1].trimmed().toInt();
	cCfg.sIP = parts[2];
	cCfg.sUserName = parts[3];
	cCfg.sPassWord = parts[4];
	cCfg.sConnectName = "HKAI";
	QVector<QString> vecTabelName;

	QStringList sList = m_sTableName.split("-");
	if (sList.size() < 0)
	{
		return false;
	}
	for (int i = 0; i < sList.size(); i++)
	{
		if (sList[i].size() > 1)
		{
			vecTabelName.push_back(sList[i]);
		}
	}
	cCfg.vecTableName = vecTabelName;
	return m_pSqlOper->initSql(&cCfg);
}
void CSqlDllOper::startWork(int nTime)
{
	if (!m_bStart)
	{
		m_pSqlOper->startWork(nTime);
		m_bStart = true;
	}
}
void CSqlDllOper::stopWork()
{
	if (m_bStart)
	{
		m_pSqlOper->stopWork();
		m_bStart = false;
	}
}
bool CSqlDllOper::exec(CDatabaseExecData & data, const int & nLock)
{
	if (m_pSqlOper == nullptr)
	{
		return false;
	}
	return m_pSqlOper->exec(data);
}
bool CSqlDllOper::loadLibrary()
{
	m_pLib = new QLibrary(m_sDllPath);
	if (!m_pLib->load()) {
		delete m_pLib;
		m_pLib = nullptr;
		return false;
	}
	CreateISqlOperFunc createFunc = (CreateISqlOperFunc)m_pLib->resolve("createISqlOper");
	if (!createFunc)
	{
		m_pLib->unload();
		delete m_pLib;
		m_pLib = nullptr;
		return false;
	}
	m_pSqlOper = createFunc();
	return true;
}

void CSqlDllOper::unLoadLibrary()
{
	if (m_pSqlOper != nullptr)
	{
		m_pSqlOper->stopWork();
	}
	if (m_pLib != nullptr)
	{
		m_pLib->unload();
		delete m_pLib;
		m_pLib = nullptr;
	}
}
